(function (window) {
    let u = {};
    //u.url  = "http://www.menwu.cn/";//正式环境
    //u.url = "http://www.menwu.com:8078/";
    //u.url = "http://wx.newamstar.com:8078";
    u.url = "localhost";
    // u.url = 'http://homestead.hd/'
    u.addrole = [];
    //登陆方法
    //获取树菜单数据
    // u.tree = function(url,gp){
    //     $(".easyui-tree").tree({
    //         url: u.url + url,
    //         method: gp||"GET",
    //         animate: true,
    //         checkbox: false,
    //         onSelect: function (node) {
    //             node.state == "closed" ? ($(this).tree('expand', node.target)) : ($(this).tree('collapse', node.target));
    //         },
    //         onClick: function (node) {
    //             if (!node.children) {
    //                 u.addTab(node.text, node.href);
    //             }
    //         }
    //     });
    // },
    u.gettree = (param = 1, data) => {
        if (param == 1) {
            $(".easyui-tree").tree({
                url: u.url + "gettree",
                method: "GET",
                animate: true,
                checkbox: false,
                onSelect: function (node) {
                    node.state == "closed" ? ($(this).tree('expand', node.target)) : ($(this).tree('collapse', node.target));
                },
                onClick: function (node) {
                    if (!node.children) {
                        u.addTab(node.text, node.href);
                    }
                }
            });
        } else if (param == 2) {
            $(".easyui-tree").tree({
                url: u.url + "gettree",
                method: "GET",
                animate: true,
                checkbox: true,
                onCheck: function (node, checked) {
                    u.addrole = [];
                    ($(this).tree('getChildren')).map(item => {
                        if (item.checkState == "indeterminate" || item.checkState == "checked")
                            u.addrole.push(item.id)
                    });
                },
                onSelect: function (node) {
                    node.state == "closed" ? ($(this).tree('expand', node.target)) : ($(this).tree('collapse', node.target));
                }
            });
        } else if (param == 3) {
            //param=3 数据源不从接口获取，直接传入
            $(".easyui-tree").tree({
                data: data,
                animate: true,
                checkbox: true,
                onCheck: function (node, checked) {
                    u.addrole = [];
                    ($(this).tree('getChildren')).map(item => {
                        if (item.checkState == "indeterminate" || item.checkState == "checked")
                            u.addrole.push(item.id)
                    });
                },
                onSelect: function (node) {
                    node.state == "closed" ? ($(this).tree('expand', node.target)) : ($(this).tree('collapse', node.target));
                },
                onLoadSuccess: function (node, data) {
                    u.addrole = [];
                    ($(this).tree('getChildren')).map(item => {
                        if (item.checkState == "indeterminate" || item.checkState == "checked")
                            u.addrole.push(item.id)
                    });
                }
            });
        }
    },
        u.addTab = function (title, url, param = 1) {
            let jq = top.jQuery, newurl = u.url + url;
            if (param == 2) {
                //param为2是需要勾选后再进行跳转;
                let sel = $("#dg").datagrid('getSelected');
                if (!sel) {
                    u.infoDialog("请勾选一条数据后在编辑");
                    return false;
                }
                let data = $("#dg").datagrid('getSelected');
                newurl = u.url + url + "?mg_id=" + data.mg_id;
            }
            if (param == 3) {
                let sel = $("#dg").datagrid('getSelected');
                if (!sel) {
                    u.infoDialog("请勾选一条数据后在编辑");
                    return false;
                }
                let data = $("#dg").datagrid('getSelected');
                newurl = u.url + url + "?id=" + data.id;
            }
            if (jq('.easyui-tabs').tabs('exists', title)) {
                jq('.easyui-tabs').tabs('select', title);
                let selTab = jq('.easyui-tabs').tabs('getSelected');
                jq('.easyui-tabs').tabs('update', {
                    tab: selTab,
                    options: {
                        content: u.createFrame(newurl)
                    }
                })
            } else {
                let content = `<iframe scrolling="auto" frameborder="0"  src=${newurl} style="width:100%;height:100%;"></iframe>`;
                jq('.easyui-tabs').tabs('add', {
                    title: title,
                    content: content,
                    closable: true
                });
            }

        },
        u.check_has_one = function (dg, param) {
            let ishave = $(dg).datagrid('getSelected');
            if (!ishave) {
                $.messager.alert('消息', '请至少勾选一条');
                return false;
            } else if (!param && ishave.length > param) {
                $.messager.alert('消息', `请至少勾选${param}条`);
            } else {
                return true;
            }
            return this;
        },
        u.initwin = newOptions => {
            let options = {width: 500, height: 300, modal: true, closed: true, maximizable: false,};
            let newoptions = $.extend(false, options, newOptions);
            $('#w').window(newoptions);
        },
        u.createFrame = url => '<iframe scrolling="auto" frameborder="0"  src="' + url + '" style="width:100%;height:100%;"></iframe>',
        u.myDataGird = function () {
            u.initwin();
            for (let i = 0; i < arguments.length; i++) {
                let args = arguments[i];
                let options = {
                    method: args.method || 'get',
                    nowrap: args.nowrap || true,
                    pagination: args.pagination || true,
                    striped: args.striped || true,
                    pageSize: args.pageSize || 50,
                    rownumbers: true,
                    fitcolumns: true,
                    singleSelect: args.singleSelect || true,
                    loadMsg: '正在加载数据，请稍候...',
                    emptyMsg: '<span>没有相关记录</span>',
                    onSelect: args.onSelect,//单击行                 参数:index,row
                    onClickRow: args.onClickRow,//获取选中行的数据     参数:index,row
                    onDblClickRow: args.onDblClickRow,//双击行       参数:index,row
                    onDblClickCell: args.onDblClickCell,//双击单元格 参数:index,field,value
                    fit: args.singleSelect || false,
                    onBeforeLoad: () => {
                    },
                    onLoadSuccess: res => {
                        if (res) {
                            $.each(res.rows, function (index, item) {
                                $('#dg').datagrid('checkRow', index);
                                if (item.flag == 'true') {
                                    if ($('#dg').length > 0) $('#dg').datagrid('checkRow', index);
                                    if ($('#dg2').length > 0) $('#dg2').datagrid('checkRow', index);
                                }
                            });
                        }
                    }
                };
                let newOption = $.extend(false, options, arguments[i]), obj = newOption['obj'],
                    hei = newOption['hei'] || 33;
                $(function () {
                    //固定高度  $('.panel-htop')是顶部搜索区域的高度
                    newOption['height'] = $(document.body).height() - $('.panel-htop').height() - hei;//固定高度，左右结构252
                    $(obj).datagrid(newOption);
                    $(obj).datagrid('getRows');
                })
            }
        }
    u.gettabs = function () {
        $('.easyui-tabs').tabs({
            onSelect: function (title, index) {
                var select = $('.easyui-tabs').tabs('getTab', index);
                if (title == "公告列表" || title == "首页" || title == "活动列表" || title == "礼品兑换列表") {
                    let url = $(select.panel('options').content).attr('src') || header + "Index/girdindex";
                    $('.easyui-tabs').tabs("update", {
                        tab: select,
                        options: {
                            title: title,
                            content: "<iframe scrolling='auto' frameborder='0'" +
                                "src='" + url + "' style='width:100%;height:100%;'></iframe>"
                        }
                    })
                } else {
                    let url = $(select.panel('options').content).attr('src') || header + "Index/first";
                }
            }
        })
    }
    u.doSearch = function () {
        $("#dg").datagrid('load', $('#form').serializeObject());
        return this;
    }
    u.clearFrom = () => $("#form").form("clear");
    u.update_role = () => $.get(u.url + 'updaterole', $('#form').serializeObject(), res => u.infoDialog("保存成功"));
    u.add_role = () => {
        let json = $('#form').serializeObject();
        json['auth'] = u.addrole;
        $.get(u.url + 'addrole', json, res => u.infoDialog("保存成功"))
    };
    //新增管理员
    u.addmanager = () => $.get(u.url + 'addmanager', $('#form').serializeObject(), res => u.infoDialog("保存成功"));
    //删除管理员
    u.deleteManager = function () {
        if (u.is_select_one("请勾选数据后再操作")) {
            let data = $("#dg").datagrid('getSelected');
            u.confirm('是否确认删除?', () => $.get(u.url + "deletemanager", {"mg_id": data.mg_id}, res => u.tool1('删除成功')))
        }
    }
    //新增商品
    u.addgood = function () {
        //let c = ue.getContent();
        let obj = $("#form").serializeObject();//editorValue editor的内容
        obj['imgurl'] = picsarr.toString();//细节多图
        obj['singleimg'] = picsarr2;//列表单图
        //obj['modelfiles']  = modefiles;//模型zip文件
        obj['X-CSRF-TOKEN'] = '{{ csrf_token() }}';
        if (!obj.goodname) {
            u.infoDialog("模型名称不能为空");
            return false;
        }
        if (!obj.imgurl) {
            u.infoDialog("商品细节图片还未上传");
            return false;
        }
        //if(!obj.modelfiles) {u.infoDialog("模型文件还未上传"); return false;}
        if (!obj.dg) {
            u.infoDialog("灯光不能为空");
            return false;
        }
        if (!obj.cztt) {
            u.infoDialog("材质贴图不能为空");
            return false;
        }
        if (!obj.fg) {
            u.infoDialog("风格不能为空");
            return false;
        }
        if (!obj.ms) {
            u.infoDialog("面数不能为空");
            return false;
        }
        if (!obj.price) {
            u.infoDialog("兑换价格不能为空");
            return false;
        }
        if (!obj.score) {
            u.infoDialog("兑换积分不能为空");
            return false;
        }
        if (!obj.singleimg) {
            u.infoDialog("图片列表图片还未上传");
            return false;
        }
        if (!obj.ssdl) {
            u.infoDialog("所属大类不能为空");
            return false;
        }
        if (!obj.sszl) {
            u.infoDialog("所属子类不能为空");
            return false;
        }
        //console.log(obj);
        $.post(u.url + 'addgood', obj, res => u.infoDialog("保存成功"))
    }
    //商品上架、下架
    u.good_sj_xj = function (param) {
        if (u.is_select_one("请勾选数据后再操作")) {
            let data = $("#dg").datagrid('getSelected'), tips = param == 1 ? '是否确认上架商品' : '是否确认下架商品';
            u.confirm(tips, () => $.get(u.url + "goodsjxj", {"id": data.id, 'param': param}, res => u.tool1('上架成功')))
        }
    }
    //新增/更新门店
    u.addshop = function (param) {
        if (param == 1) {
            //新增门店
            $('#w1').window({
                title: '新增门店信息', width: 600, height: 400, modal: true, onClose: function () {
                    u.reloadTable();
                    $("#form2").form("clear");
                }
            });
            $('#w1').window('open');
        } else if (param == 2) {
            //编辑门店
            if (u.is_select_one("请勾选数据后再操作")) {
                let data = $("#dg").datagrid('getSelected');
                $.get(u.url + 'shopdetail', {id: data.id}, res => {
                    $('.shopname').textbox('setValue', res.data.shopname);
                    $('.shopaddress').textbox('setValue', res.data.shopaddress);
                    $('.lxr').textbox('setValue', res.data.lxr);
                    $('.lxdh').textbox('setValue', res.data.lxdh);
                    $('.shopid').attr('value', res.data.id);
                }, 'json')

                $('#w1').window({
                    title: '编辑门店信息', width: 600, height: 400, modal: true, onClose: function () {
                        u.reloadTable();
                        $("#form2").form("clear");
                    }
                });
                $('#w1').window('open');
            }
        }
    }
    u.delshop = function () {
        if (u.is_select_one("请勾选数据后再操作")) {
            let data = $("#dg").datagrid('getSelected');
            u.confirm('是否确认删除?', () => $.get(u.url + "deleteshop", {"id": data.id}, res => {
                u.tool1('删除成功');
            }))
        }
    }
    //保存数据
    u.saveshop = function () {
        let formdata = $("#form2").serializeObject(), tips = '';
        tips = formdata.shopid != "" ? '更新门店信息成功' : '新增门店信息成功';
        u.confirm('确认保存数据吗?', () => $.get(u.url + "add_update_shop", formdata, res => u.tool1(tips)));
    }
    //物流信息录入
    u.wlxxlr = function () {
        if (u.is_select_one("请勾选数据后再操作")) {
            let data = $("#dg").datagrid('getSelected');
            $('#w1').window({
                title: '物流信息录入', width: 600, height: 150, modal: true, onClose: function () {
                    u.reloadTable();
                    $("#form2").form("clear");
                }
            });
            $('#w1').window('open');
        }
    }
    //录入更新物流单号
    u.savewldh = function () {
        let formdata = $("#form2").serializeObject();
        let data = $("#dg").datagrid('getSelected');
        formdata["id"] = data.id;
        u.confirm('确认保存数据吗?', () => $.get(u.url + "savewldh", formdata, res => u.tool1("更新物流单号成功")));
    }
    //兑换记录作废
    u.dhjlzf = function () {
        if (u.is_select_one("请勾选数据后再操作")) {
            let data = $("#dg").datagrid('getSelected');
            u.confirm('是否确认作废兑换记录?', () => $.get(u.url + "dhjlzf", data, res => u.tool1("作废兑换记录成功")));
        }
    }
    u.edituserinfo = function () {
        $('#dialog').window({title: '用户信息编辑', width: 600, height: 500, modal: true, onClose: () => u.reloadTable()});
        let data = $("#dg").datagrid('getSelected');
        $.get($api.url + 'getuserinfo', {"id": data.id}, res => {
            let [obj] = res;
            $('#updateform').form('load', obj);
            $('#dialog').window('open');
        });
    }
    u.updateuserinfo = function () {
        let obj = $("#updateform").serializeObject();
        let data = $("#dg").datagrid('getSelected');
        obj["id"] = data.id;
        $.get($api.url + "updateuserinfo", obj, res => u.infoDialog("更新成功"));
    }
    u.regbtn = function () {
        // email: "qeqe@qq.com"
        // password2: "13313"
        // password3: "131313"
        // phone: "123456"
        // token1: "f9e358928003a5f58d57592c90b6c5f1"
        // validcode: "a9jza"
        let obj = $("#regform").serializeObject();
        $.post(u.url + "appreg", obj, res => {
            if (res.flag == "success") {
                $("#loginbox-show").show();
                $("#regbox-show").hide();
                $('.login3-title li').removeClass();
                $("#loginbox").addClass("active");
            }
            layer.msg(res.msg);
        }, 'json');
    }
    /**
     * 网站登陆方法
     */
    u.applogin = function () {
        let obj = $("#loginform").serializeObject();
        //console.log(obj);
        //window.location.href='view_index';
        $.post(u.url + "applogin", obj, res => res.flag === "success" ? window.location.href = 'view_index' : layer.msg(res.msg), 'json');
    }
    /**
     * 登陆账号智能检测
     */
    u.verify_login = function () {

    }
    u.info_dialog = function (str) {
        $.messager.alert('提示消息', str, 'info');
    }
    u.tool1 = function (str) {
        u.infoDialog(str);
        u.reloadTable();
        u.winclose("#w1");
    }
    //关闭窗体
    u.winclose = obj => {
        $(obj).window("close")
    };
    u.reloadTable = () => $("#dg").datagrid('reload');
    //确认是否勾选，
    u.is_select_one = msg1 => {
        let data = $("#dg").datagrid('getSelected');
        if (!data) {
            u.infoDialog(msg1);
            return false;
        }
        return true;
    }
    u.infoDialog = str => {
        $.messager.alert('提示消息', str, 'info');
    }
    u.confirm = function (tips, callback) {
        $.messager.confirm('提示信息', tips, function (r) {
            if (r) callback();
        });
    }
    /**
     * 点击购买模型
     */
    u.modelversion = function () {
        let obj = {down_type, gid} = $("#gform").serializeObject();
        $.get(u.url + "querystate",{gid},res=>{
            //查询当前商品当前用户是否已经购买过，并且是否在有效期内,如果在有效期内，就提示已购买，不需要重新购买
        })
        layer.confirm('是否确认跳转支付宝页面?', {
            btn: ['是', '否'] //按钮
        }, function () {
            window.open(`${u.url}trade_pc_pay?down_type=${down_type}&gid=${gid}`);
            layer.confirm('是否确认支付完成?', {
                btn: ['是', '否'] //按钮
            }, function () {
                //手动点击确认订单状态
                $.get(`${u.url}query_pay_order`, res => {
                    if (res.flag == 1) {
                        location.reload();
                    }
                })
            }, function () {

            });
        }, function () {

        });
    }
    /**
     * 扩展jq对象
     * 调用方式:$("#input1").alertWhileClick()
     * @return 返回扩展之后的jq对象
     *
     */
    $.fn.extend({
        serializeObject: function () {
            let o = {}, a = this.serializeArray();
            $.each(a, function () {
                if (o[this.name] !== undefined) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        },
    });
    window.$api = u;
})(window);
/**
 * 扩展jq对象
 * 调用方式:$.alertWhileClick()
 * @return 返回扩展之后的jq对象
 *
 */
$.extend({
    formatDate: function (date) {
        let y = date.getFullYear(), m = date.getMonth() + 1, d = date.getDate();
        return y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d);
    },
    myParse: function (s) {
        if (!s) return new Date();
        let ss = (s.split('-')), y = parseInt(ss[0], 10), m = parseInt(ss[1], 10), d = parseInt(ss[2], 10);
        return (!isNaN(y) && !isNaN(m) && !isNaN(d)) ? new Date(y, m - 1, d) : new Date();
    },
    carousel: function () {
        let swiper = new Swiper('.swiper-container', {
            pagination: '.swiper-pagination',
            paginationClickable: true,
            paginationBulletRender: function (swiper, index, className) {
                return '<span class="' + className + '">' + (index + 1) + '</span>';
            }
        });
    }
})
